package com.kewill.jira.util;

import com.kewill.jira.common.DaoAnnotation;
import com.kewill.jira.common.JiraAttribute;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * Created by YanJun on 2016/7/14.
 */
public class DaoUtil {
    private static HashMap<String,Object> implDaoCache = new HashMap<String,Object>();
    public static void setDao(Object obj) throws InvocationTargetException, IllegalAccessException {
        Method[] methodArray = obj.getClass().getDeclaredMethods();
        for(Method method:methodArray){
            if(method.getName().startsWith("set") && method.isAnnotationPresent(DaoAnnotation.class)){
                DaoAnnotation daoAnnotation = method.getAnnotation(DaoAnnotation.class);
                String daoImplClassName = daoAnnotation.value();
                String daoImplClassFullName = JiraAttribute.DAOIMPL_PACKAGE + "." + daoImplClassName;
                method.invoke(obj,createNewObj(daoImplClassFullName));
            }
        }
    }

    private static Object createNewObj(String classFullName){
        Object obj = null;
        try {
            if(implDaoCache.containsKey(classFullName)){
                obj = implDaoCache.get(classFullName);
            }else {
                Class clazz = Class.forName(classFullName);
                obj = clazz.newInstance();
                implDaoCache.put(classFullName,obj);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
